package com.design.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.design.reggie.common.BaseContext;
import com.design.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //调用Spring核心包的字符串匹配类
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取本次请求的URI
        String requestURI = request.getRequestURI();
//        log.info("拦截到请求：{}", requestURI);


        // 定义不需要处理的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login"
        };

        // 判断本次请求是否需要处理
        boolean check = check(requestURI, urls);

        // 如果不需要处理，则直接放行
        if (check) {
            log.info("当前路径 {} 不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        // 如果已经登录，则直接放行（PC后台版）
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户id为{}", request.getSession().getAttribute("employee"));

            // 利用ThreadLocal保存当前登录用户的id
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }

        // 如果已经登录，则直接放行（前台用户版）
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为{}", request.getSession().getAttribute("user"));

            // 利用ThreadLocal保存当前登录用户的id
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        // 如果未登录，则返回未登录结果
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;


    }

    /**
     * @param urls 之前定义的可以放行的url地址数组
     * @param requestURI 客户端打来的url地址
     * @return  返回值boolean值，true的话就是我们可以放行的目标
     */
    public boolean check(String requestURI, String[] urls) {
        for (String url : urls) {
            //遍历的同时调用PATH_MATCHER来对路径进行匹配
            boolean match = PATH_MATCHER.match(url, requestURI);
            //匹配到了可以放行的路径，直接放行
            if (match) {
                return true;
            }
        }
        //否则就是没有匹配到，不予放行
        return false;
    }
}
